package com.shun.auth.action;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.shun.auth.dto.UserLoginDto;
import com.shun.auth.service.AuthService;
import com.shun.common.R;
import com.shun.common.constants.CheckType;
import com.shun.common.utils.ServletUtils;
import com.shun.upms.api.ShunUpmsApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 平台授权服务处理
 *
 * @author clever
 * @since 2021-09-24
 */
@Slf4j
@RequestMapping("/auth")
@RestController
public class ShunAuthAction extends ShunAuthBaseAction{

    @Autowired
    private ShunUpmsApi shunUpmsApi;

    @Autowired
    private AuthService authService;

    /**
     * 用户登录处理
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody @Validated UserLoginDto userLoginDto) {
        String userAgent = ServletUtils.getRequest().getHeader("user-agent");
        String clientIp = ServletUtil.getClientIP(ServletUtils.getRequest());
        log.debug("用户登录信息：{},clientIp:{},userAgent:{}",userLoginDto,clientIp,userAgent);
        R result = null;
        if(userLoginDto.getCheckType().equals(CheckType.ACC.getCode())){
            String acc = decryptStr(userLoginDto.getAccount());
            String pwd = decryptStr(userLoginDto.getPassword());
            result =  shunUpmsApi.checkUserPasswd(acc,pwd);
        } else if(userLoginDto.getCheckType().equals(CheckType.SMS.getCode())){
            result =  shunUpmsApi.checkUserTel(userLoginDto.getTelNo());
        }
        log.debug("检验返回结果信息:{}",result);
        if(result.ifSuc()){
            StpUtil.login(result.getData().toString());
            log.debug("x-token:{}",StpUtil.getTokenValue());
            result.setData(StpUtil.getTokenValue());
        }
        //异步处理新增登录日志
        authService.addLoginLog(userLoginDto,decryptStr(userLoginDto.getAccount()),result,userAgent,clientIp);
        return result;
    }

    /**
     * 管理用户退出
     * @return
     */
    @GetMapping("/logout")
    public R logout(){
        String userId = StpUtil.getLoginIdAsString();
        log.debug("退出用户ID：{}",userId);
        StpUtil.logout();
        return R.suc();
    }
}
